POJ-2718 Smallest Difference(STL全排列 + 输入流魔改)

描述

传送门:Smallest Difference

Given a number of distinct decimal digits, you can form one integer by choosing a non-empty subset of these digits and writing them in some order. The remaining digits can be written down in some order to form a second integer. Unless the resulting integer is 0, the integer may not start with the digit 0.

For example, if you are given the digits 0, 1, 2, 4, 6 and 7, you can write the pair of integers 10 and 2467. Of course, there are many ways to form such pairs of integers: 210 and 764, 204 and 176, etc. The absolute value of the difference between the integers in the last pair is 28, and it turns out that no other pair formed by the rules above can achieve a smaller difference.

输入描述

The first line of input contains the number of cases to follow. For each case, there is one line of input containing at least two but no more than 10 decimal digits. (The decimal digits are 0, 1, …, 9.) No digit appears more than once in one line of the input. The digits will appear in increasing order, separated by exactly one blank space.

输出描述

For each test case, write on a single line the smallest absolute difference of two integers that can be written from the given digits as described by the rules above.

示例

输入

1
2
1
0 1 2 4 6 7

输出

1
28

题解

题目大意

给定若干位十进制数,你可以通过选择一个非空子集并以某种顺序构建一个数。剩余元素可以用相同规则构建第二个数。除非构造的数恰好为0,否则不能以0打头。

思路

若总数字数是偶数,组出来的两个数字的长度必相等,若是奇数,长度必差一
对所有数字排列,求 data[:N//2], data[N//2:] 的差及可 AC
注意须排除有前导 0 的情况。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <sstream>

using namespace std;

int solve(vector<int>& data) {
int N = data.size();
int len = N / 2;

int min_diff = 1000000000;
do {
// data[:len], data[len:]

// prefix 0
if (len != 1 && data[0] == 0) continue;
if (N - len != 1 && data[len] == 0) continue;

int first = 0;
for (int i = 0; i < len; i++)
first = first * 10 + data[i];

int second = 0;
for (int i = len; i < N; i++)
second = second * 10 + data[i];

if (abs(first - second) < min_diff)
min_diff = abs(first - second);
} while (next_permutation(data.begin(), data.end()));

return min_diff;
}

int main() {
ios::sync_with_stdio(false);

int T;
cin >> T;

string temp;
getline(cin, temp); // eat the endl

while (T--) {
string line;
getline(cin, line);

istringstream iss(line);
vector<int> data;
int inp;
while (iss >> inp) {
data.push_back(inp);
}

cout << solve(data) << endl;
}

return 0;
}